
const express = require('express');
const session = require('express-session');
const router = express.Router();
const db = require('./db');
const moment = require('moment');
const { connect } = require('http2');

// 教学生，创建订单
// router.post("/create", (req, res) => {
//     // 获取请求参数
//     const { address, note, goods } = req.body;
//     const userId = req.session.userId;
//     if (!userId) {
//         res.status(400).json({
//             code: 2,
//             msg: "未登录"
//         });
//     }
//     // 构建订单对象
//     const order = {
//         user_user_id: userId, // 假设使用 session 存储用户的 ID
//         price: 0, // 初始化价格为 0
//         address_name: '',
//         address_tel: '',
//         address_area: '',
//         address_detail: '',
//         note: note,
//         is_pay: false, // 默认未支付
//         is_cancel: false, // 默认未取消
//         create_time: moment().format('YYYY-MM-DD HH:mm:ss'),
//         update_time: moment().format('YYYY-MM-DD HH:mm:ss')
//     };




//     const getAddressQuery = 'SELECT * FROM tpadmin_user_address WHERE id = ? AND user_user_id = ?';
//     db.connection.query(getAddressQuery, [address, userId], (error, results) => {
//         if (error) {
//             console.error('获取收货地址失败:', error);
//             res.status(200).json({ msg: '获取收货地址失败' });
//         } else {
//             if (results.length === 0) {
//                 res.status(200).json({ code: 0, msg: '未找到指定的收货地址' });
//             } else {
//                 // 通过address_id获取收货地址信息
//                 const address = results[0];
//                 order.address_name = address.name;
//                 order.address_tel = address.tel;
//                 order.address_area = address.area;
//                 order.address_detail = address.detail;
//                 //写入tpadmin_user_order表
//                 const insertOrderQuery = 'INSERT INTO tpadmin_user_order SET ?';
//                 db.connection.query(insertOrderQuery, order, (error, results) => {
//                     if (error) {
//                         console.error('订单创建失败：', error);
//                         res.status(200).json({ code: 0, msg: '订单创建失败' });
//                     } else {
//                         var order_id = results.insertId;
//                         // 遍历goods数组
//                         goods.forEach(good => {
//                             //查询价格和库存数量
//                             db.connection.query(`SELECT price,num FROM tpadmin_goods_goods WHERE id=?`, good.id, (err, results) => {
//                                 if (err) {
//                                     console.error('订单创建失败：', error);
//                                     res.status(200).json({ code: 0, msg: '订单创建失败' });
//                                 } else {
//                                     console.log('%cbackend\orderApi.js:74 result[0],count', 'color: #007acc;', results[0].num, good.count);
//                                     console.log('%cbackend\orderApi.js:74 "库存不足"', 'color: #007acc;', "库存不足");
//                                     // if (results[0].num < good.count) {
//                                     //     res.status(200).json({ code: 0, msg: "库存不足" })
//                                     // } else {
//                                     //写入tpadmin_user_order_goods表
//                                     const order_goods = {
//                                         user_order_id: order_id,
//                                         goods_goods_id: good.id,
//                                         count: good.count,
//                                         price: results[0].price,
//                                         create_time: moment().format('YYYY-MM-DD HH:mm:ss'),
//                                         update_time: moment().format('YYYY-MM-DD HH:mm:ss')
//                                     }
//                                     const insertOrderGoodsQuery = 'INSERT INTO tpadmin_user_order_goods SET ?';
//                                     db.connection.query(insertOrderGoodsQuery, order_goods, (error, results) => {
//                                         if (error) {
//                                             console.error('订单创建失败：', error);
//                                             res.status(500).json({ code: 0, msg: '订单创建失败' });
//                                         } else {
//                                             res.status(200).json({
//                                                 code: 1,
//                                                 msg: '订单创建成功',
//                                                 data: results.insertId,
//                                                 url: 'http://localhost:10086/',
//                                                 wait: 3,
//                                             });
//                                         }
//                                     })
//                                 }
//                                 // }
//                             })
//                         })

//                     }
//                 });
//             }
//         }
//     });
// });
// router.post("/create", (req, res) => {
//     const { address, note, goods } = req.body;
//     const userId = req.session.userId;

//     if (!userId) {
//         res.status(400).json({
//             code: 2,
//             msg: "未登录"
//         });
//         return;
//     }

//     // 构建订单对象
//     const order = {
//         user_user_id: userId,
//         price: 0,
//         address_name: '',
//         address_tel: '',
//         address_area: '',
//         address_detail: '',
//         note: note,
//         is_pay: false,
//         is_cancel: false,
//         create_time: moment().format('YYYY-MM-DD HH:mm:ss'),
//         update_time: moment().format('YYYY-MM-DD HH:mm:ss')
//     };

//     // 获取收货地址信息
//     function getAddress() {
//         return new Promise((resolve, reject) => {
//             const getAddressQuery = 'SELECT * FROM tpadmin_user_address WHERE id = ? AND user_user_id = ?';
//             db.connection.query(getAddressQuery, [address, userId], (error, results) => {
//                 if (error) {
//                     console.error('获取收货地址失败:', error);
//                     reject(error);
//                 } else {
//                     if (results.length === 0) {
//                         reject({ code: 0, msg: '未找到指定的收货地址' });
//                     } else {
//                         const address = results[0];
//                         order.address_name = address.name;
//                         order.address_tel = address.tel;
//                         order.address_area = address.area;
//                         order.address_detail = address.detail;
//                         resolve();
//                     }
//                 }
//             });
//         });
//     }

//     // 创建订单
//     function createOrder() {
//         return new Promise((resolve, reject) => {
//             const insertOrderQuery = 'INSERT INTO tpadmin_user_order SET ?';
//             db.connection.query(insertOrderQuery, order, (error, results) => {
//                 if (error) {
//                     console.error('订单创建失败：', error);
//                     reject(error);
//                 } else {
//                     resolve(results.insertId);
//                 }
//             });
//         });
//     }

//     // 创建订单商品
//     function createOrderGoods(orderId, good) {
//         return new Promise((resolve, reject) => {
//             db.connection.query(`SELECT price,num FROM tpadmin_goods_goods WHERE id=?`, good.id, (err, results) => {
//                 if (err) {
//                     console.error('订单创建失败：', err);
//                     reject(err);
//                 } else {
//                     if (results[0].num < good.count) {
//                         reject("库存不足");
//                     } else {
//                         const order_goods = {
//                             user_order_id: orderId,
//                             goods_goods_id: good.id,
//                             count: good.count,
//                             price: results[0].price,
//                             create_time: moment().format('YYYY-MM-DD HH:mm:ss'),
//                             update_time: moment().format('YYYY-MM-DD HH:mm:ss')
//                         };
//                         const insertOrderGoodsQuery = 'INSERT INTO tpadmin_user_order_goods SET ?';
//                         db.connection.query(insertOrderGoodsQuery, order_goods, (error, results) => {
//                             if (error) {
//                                 console.error('订单创建失败：', error);
//                                 reject(error);
//                             } else {
//                                 resolve(results.insertId);
//                             }
//                         });
//                     }
//                 }
//             });
//         });
//     }

//     getAddress()
//     .then(() => createOrder())
//     .then(orderId => {
//         createdOrderId = orderId; // 保存创建的订单ID以便后续使用
//         return Promise.all(goods.map(good => createOrderGoods(orderId, good)));
//     })
//     .then(() => {
//         res.status(200).json({
//             code: 1,
//             msg: '订单创建成功',
//             data: createdOrderId, // 使用创建的订单ID作为数据
//             url: 'http://localhost:10086/',
//             wait: 3
//         });
//     })
//     .catch(error => {
//         console.log('%cbackend\orderApi.js:221 error', 'color: #007acc;', error);
//         res.status(200).json({
//             code: 0,
//             msg: '订单创建失败',
//             error: error
//         });
//     });
// });
router.post("/create", (req, res) => {
    const { address, note, goods } = req.body;
    const userId = req.session.userId;
    console.log('[订单创建] 请求参数:', { address, note, goods, userId });
    if (!userId) {
        console.warn('[订单创建] 未登录用户尝试下单');
        res.status(400).json({
            code: 2,
            msg: "未登录"
        });
        return;
    }
    //扣除用户积分
    function deductPoints(userId, orderTotalPrice) {
      return new Promise((resolve, reject) => {
        // 获取用户当前积分值
        const getPointsQuery = 'SELECT points FROM tpadmin_user_user WHERE id = ?';
        db.connection.query(getPointsQuery, userId, (error, results) => {
          console.log('[订单创建] 查询用户积分:', userId, results);
          if (error) {
            console.error('[订单创建] 获取用户积分失败:', error);
            reject(error);
          } else {
            const currentPoints = results[0].points;
            if (currentPoints < orderTotalPrice) {
              console.warn('[订单创建] 用户积分不足:', currentPoints, orderTotalPrice);
              reject({ code: 0, msg: '用户积分不足' });
            } else {
              const newPoints = -orderTotalPrice; // 假设每消费1元扣除1积分
              const updatePointsQuery = 'UPDATE tpadmin_user_user SET points = ? WHERE id = ?';
              db.connection.query(updatePointsQuery, [currentPoints + newPoints, userId], (err, res) => {
                if (err) {
                  console.error('[订单创建] 更新用户积分失败:', err);
                  reject(err);
                } else {
                  console.log('[订单创建] 扣除积分成功:', userId, orderTotalPrice);
                  resolve(orderTotalPrice);
                }
              });
            }
          }
        });
      });
    }
    // 获取订单总价
    function getOrderPrice() {
        return new Promise((resolve, reject) => {
            let totalPrice = 0;
            let count = 0;
            for (const good of goods) {
                db.connection.query('SELECT price FROM tpadmin_goods_goods WHERE id=?', good.id, (error, results) => {
                    console.log('[订单创建] 查询商品价格:', good.id, results);
                    if (error) {
                        console.error('[订单创建] 获取商品价格失败:', error);
                        reject(error);
                    } else {
                        if (results.length === 0) {
                            console.warn('[订单创建] 未找到指定商品:', good.id);
                            reject({ code: 0, msg: '未找到指定的商品' });
                        } else {
                            const { price } = results[0];
                            totalPrice += price * good.count;
                            count++;
                            if (count === goods.length) {
                                console.log('[订单创建] 订单总价:', totalPrice);
                                resolve(totalPrice);
                            }
                        }
                    }
                });
            }
        });
    }
    // 构建订单对象
    function buildOrder(price) {
        const order = {
            user_user_id: userId,
            price: price,
            address_name: '',
            address_tel: '',
            address_area: '',
            address_detail: '',
            note: note,
            is_pay: false,
            is_cancel: false,
            create_time: moment().format('YYYY-MM-DD HH:mm:ss'),
            update_time: moment().format('YYYY-MM-DD HH:mm:ss')
        };
        console.log('[订单创建] 构建订单对象:', order);
        return order;
    }
    // 获取收货地址信息
    function getAddress(order) {
        return new Promise((resolve, reject) => {
            const getAddressQuery = 'SELECT * FROM tpadmin_user_address WHERE id = ? AND user_user_id = ?';
            db.connection.query(getAddressQuery, [address, userId], (error, results) => {
                console.log('[订单创建] 查询收货地址:', address, userId, results);
                if (error) {
                    console.error('[订单创建] 获取收货地址失败:', error);
                    reject(error);
                } else {
                    if (results.length === 0) {
                        console.warn('[订单创建] 未找到指定收货地址:', address);
                        reject({ code: 0, msg: '未找到指定的收货地址' });
                    } else {
                        const addressObj = results[0];
                        order.address_name = addressObj.name;
                        order.address_tel = addressObj.tel;
                        order.address_area = addressObj.area;
                        order.address_detail = addressObj.detail;
                        console.log('[订单创建] 收货地址信息:', order);
                        resolve(order);
                    }
                }
            });
        });
    }
    // 创建订单
    function createOrder(order) {
        return new Promise((resolve, reject) => {
            const insertOrderQuery = 'INSERT INTO tpadmin_user_order SET ?';
            db.connection.query(insertOrderQuery, order, (error, results) => {
                if (error) {
                    console.error('[订单创建] 订单写入失败:', error);
                    reject(error);
                } else {
                    console.log('[订单创建] 订单写入成功，订单ID:', results.insertId);
                    resolve(results.insertId);
                }
            });
        });
    }
    // 创建订单商品
    function createOrderGoods(orderId, good) {
        return new Promise((resolve, reject) => {
            db.connection.query('SELECT price FROM tpadmin_goods_goods WHERE id=?', good.id, (err, results) => {
                if (err) {
                    console.error('[订单创建] 查询商品价格失败:', err);
                    reject(err);
                } else {
                    const order_goods = {
                        user_order_id: orderId,
                        goods_goods_id: good.id,
                        count: good.count,
                        price: results[0].price,
                        create_time: moment().format('YYYY-MM-DD HH:mm:ss'),
                        update_time: moment().format('YYYY-MM-DD HH:mm:ss')
                    };
                    const insertOrderGoodsQuery = 'INSERT INTO tpadmin_user_order_goods SET ?';
                    db.connection.query(insertOrderGoodsQuery, order_goods, (error, results) => {
                        if (error) {
                            console.error('[订单创建] 订单商品写入失败:', error);
                            reject(error);
                        } else {
                            console.log('[订单创建] 订单商品写入成功:', order_goods);
                            resolve(results.insertId);
                        }
                    });
                }
            });
        });
    }
    getOrderPrice()
        .then(price => deductPoints(userId,price))
        .then(price => buildOrder(price))
        .then(order => getAddress(order))
        .then(order => createOrder(order))
        .then((orderId) => {
            return Promise.all(goods.map(good => createOrderGoods(orderId, good)));
        })
        .then(() => {
            console.log('[订单创建] 订单创建流程全部完成');
            res.status(200).json({
                code: 1,
                msg: '订单创建成功',
                url: 'http://localhost:10086/',
                wait: 3
            });
        })
        .catch(error => {
            console.error('[订单创建] 订单创建流程出错:', error);
            res.status(200).json({
                code: 0,
                msg: '订单创建失败',
                error: error
            });
        });
});

// 查询订单列表
// router.get("/list", (req, res) => {
//     const userId = req.session.userId;
//     if (!userId) {
//         res.status(400).json({ code: 2 });
//     }
//     const query = `select * from tpadmin_user_order WHERE user_user_id =?`;
//     db.connection.query(query, [userId], (error, results) => {
//         console.log('%cbackend\addressApi.js:47 results', 'color: #007acc;', results);
//         if (error) {
//             console.error('登录失败:', error);
//             res.status(500).json({ msg: '登录失败' });
//         } else {
//             if (results.length === 0) {
//                 res.status(200).json({ code: 1, msg: '暂无数据' });
//             } else {
//                 res.status(200).json({ code: 1, msg: '', data: results })
//             }
//         }
//     })
// })

router.get("/list", (req, res) => {
    const userId = req.session.userId;
    if (!userId) {
      res.status(400).json({ code: 2 });
      return;
    }
    
    const query = `
      SELECT o.*, og.*, g.image AS goods_image ,o.price AS order_price
      FROM tpadmin_user_order AS o
      LEFT JOIN tpadmin_user_order_goods AS og ON o.id = og.user_order_id
      LEFT JOIN tpadmin_goods_goods AS g ON og.goods_goods_id = g.id
      WHERE o.user_user_id = ?
    `;
    
    db.connection.query(query, [userId], (error, results) => {
      if (error) {
        console.error('查询订单列表失败:', error);
        res.status(500).json({ msg: '查询订单列表失败' });
      } else {
        if (results.length === 0) {
          res.status(200).json({ code: 1, msg: '暂无数据' });
        } else {
          const orders = {};
          for (const row of results) {
            const orderId = row.user_order_id;
            if (!orders[orderId]) {
              // 创建新订单对象
              orders[orderId] = {
                id:orderId,
                user_user_id: row.user_user_id,
                price: row.order_price,
                address_name: row.address_name,
                address_tel: row.address_tel,
                address_area: row.address_area,
                address_detail: row.address_detail,
                note: row.note,
                is_pay: row.is_pay,
                is_cancel: row.is_cancel,
                create_time: row.create_time,
                update_time: row.update_time,
                user_order_goods: []
              };
            }
            
            // 添加当前订单的商品信息到 user_order_goods 数组中
            if (row.goods_goods_id) {
              orders[orderId].user_order_goods.push({
                id: row.goods_goods_id,
                user_order_id: row.user_order_id,
                count: row.count,
                price: row.price,
                create_time: row.create_time,
                update_time: row.update_time,
                goods_goods: {
                  id: row.goods_goods_id,
                  image: `https://shaoermofangzhandui.asia/img/${row.goods_image}`
                }
              });
            }
          }
          
          // 将订单对象数组转换为数组格式
          const orderList = Object.values(orders);
          
          res.status(200).json({
            code: 1,
            msg: '',
            data: orderList,
            url: 'http://localhost:10086/',
            wait: 3
          });
        }
      }
    });
  });

//查询订单详情
router.get("/show", (req, res) => {
  const orderId = req.query.id;

  if (!orderId) {
    res.status(400).json({ code: 0, msg: '缺少订单id参数' });
    return;
  }

  const query = `
    SELECT o.*, g.*, og.count AS goods_count, g.price AS goods_price, g.create_time AS goods_create_time, g.update_time AS goods_update_time,g.name AS 
    FROM tpadmin_user_order AS o
    LEFT JOIN tpadmin_user_order_goods AS og ON o.id = og.user_order_id
    LEFT JOIN tpadmin_goods_goods AS g ON og.goods_goods_id = g.id
    WHERE o.id = ?
  `;

  db.connection.query(query, [orderId], (error, results) => {
    if (error) {
      console.error('查询订单详情失败:', error);
      res.status(500).json({ code: 0, msg: '查询订单详情失败' });
    } else {
      if (results.length === 0) {
        res.status(200).json({ code: 0, msg: '订单不存在' });
      } else {
        const order = {
          id: results[0].id,
          user_user_id: results[0].user_user_id,
          price: results[0].order_price,
          address_name: results[0].address_name,
          address_tel: results[0].address_tel,
          address_area: results[0].address_area,
          address_detail: results[0].address_detail,
          note: results[0].note,
          is_pay: results[0].is_pay,
          is_cancel: results[0].is_cancel,
          create_time: results[0].create_time,
          update_time: results[0].update_time,
          user_order_goods: []
        };

        for (const row of results) {
          if (row.goods_goods_id) {
            const goods = {
              id: row.goods_goods_id,
              user_order_id: row.user_order_id,
              count: row.goods_count,
              price: row.goods_price,
              create_time: row.goods_create_time,
              update_time: row.goods_update_time,
              goods_goods: {
                id: row.goods_goods_id,
                name: row.goods_name,
                image: `https://shaoermofangzhandui.asia/img/${row.goods_image}`
              }
            };
            order.user_order_goods.push(goods);
          }
        }

        res.status(200).json({
          code: 1,
          msg: '',
          data: order,
          url: req.headers.referer,
        });
      }
    }
  });
});
  

// 取消订单
router.post("/cancel", (req, res) => {
    res.status(200).json({
        code: 1
    }
    )
})


//查看所有订单
router.get('/orders', (req, res) => {
    const query = `
      SELECT tpadmin_user_order.id AS order_id,
             tpadmin_user_order.user_user_id,
             tpadmin_user_order.price,
             tpadmin_user_order.address_name,
             tpadmin_user_order.address_tel,
             tpadmin_user_order.address_area,
             tpadmin_user_order.address_detail,
             tpadmin_user_order.note,
             tpadmin_user_order.is_pay,
             tpadmin_user_order.is_cancel,
             tpadmin_user_order.create_time,
             tpadmin_user_order.update_time,
             GROUP_CONCAT(tpadmin_user_order_goods.goods_goods_id SEPARATOR ',') AS goods_ids,
             GROUP_CONCAT(tpadmin_user_order_goods.count SEPARATOR ',') AS counts
      FROM tpadmin_user_order
      INNER JOIN tpadmin_user_order_goods ON tpadmin_user_order.id = tpadmin_user_order_goods.user_order_id
      GROUP BY tpadmin_user_order.id
      LIMIT 100;
    `;
  
    db.connection.query(query, (error, results) => {
      if (error) {
        console.error('查询订单失败:', error);
        return res.status(500).json({ error: '查询订单失败' });
      }
  
      const orders = results.map((row) => ({
        order_id: row.order_id,
        user_user_id: row.user_user_id,
        price: row.price,
        address_name: row.address_name,
        address_tel: row.address_tel,
        address_area: row.address_area,
        address_detail: row.address_detail,
        note: row.note,
        is_pay: row.is_pay,
        is_cancel: row.is_cancel,
        create_time: row.create_time,
        update_time: row.update_time,
        goods: formatGoods(row.goods_ids, row.counts)
      }));
  
      res.json(orders);
    });
  });
  
  // 辅助函数：将商品ID列表和数量列表转换为商品数组
  function formatGoods(goodsIds, counts) {
    const goodsIdsArr = goodsIds.split(',');
    const countsArr = counts.split(',');
  
    const goodsArr = [];
    for (let i = 0; i < goodsIdsArr.length; i++) {
      const item = {
        goods_goods_id: goodsIdsArr[i],
        count: countsArr[i]
      };
      goodsArr.push(item);
    }
  
    return goodsArr;
  }
module.exports = router;
